// cloudfunctions/login/index.js
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('Login function invoked with event:', event)
  const wxContext = cloud.getWXContext()
  const { OPENID } = wxContext
  const { nickname, avatar } = event

  console.log('OPENID:', OPENID)
  console.log('nickname:', nickname)
  console.log('avatar:', avatar)

  // 参数验证
  if (!nickname || !avatar) {
    console.log('Missing nickname or avatar')
    return {
      success: false,
      message: '缺少用户信息，无法创建新用户'
    }
  }

  try {
    // 检查用户是否已存在
    const user = await db.collection('users').where({
      openId: OPENID
    }).get()

    console.log('Existing users:', user.data)

    if (user.data.length === 0) {
      // 新用户，创建记录
      const res = await db.collection('users').add({
        data: {
          openId: OPENID,
          nickname: nickname,
          avatar: avatar,
          createdAt: new Date()
        }
      })
      console.log('New user created with ID:', res._id)
      return {
        success: true,
        userId: res._id
      }
    } else {
      // 已存在，返回用户ID
      console.log('User already exists with ID:', user.data[0]._id)
      return {
        success: true,
        userId: user.data[0]._id
      }
    }
  } catch (err) {
    console.error('Login function error:', err)
    // 根据错误类型返回不同的消息
    if (err.code === 11000) { // 假设11000是重复键错误（具体根据实际情况调整）
      return {
        success: false,
        message: '用户已存在，但数据异常，请联系管理员'
      }
    }
    return {
      success: false,
      message: '登录过程中发生错误，请稍后重试',
      error: err
    }
  }
}
